//
//  VideoCell.m
//  RtspClient
//
//  Created by qi tan on 2024/1/4.
//  Copyright © 2024 Andres Rojas. All rights reserved.
// 视频mp4存放于NSTemporaryDirectory()中；截图存放于沙盒中。

#import "VideoCell.h"
#import <AVFoundation/AVFoundation.h>

@interface VideoCell ()
@property (weak, nonatomic) IBOutlet UIImageView *imageViewIcon;
@property (weak, nonatomic) IBOutlet UIImageView *videoPlayIcon;
@property (weak, nonatomic) IBOutlet UILabel *lblName;
@property (weak, nonatomic) IBOutlet UILabel *lblDesc;
@end


@implementation VideoCell
+ (instancetype)videoImageCellWithTableView:(UITableView *)tableView {
    static NSString *ID = @"video_image_cell";
    VideoCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if(cell == nil) {
        cell =  [[[NSBundle mainBundle] loadNibNamed:@"VideoCell" owner:nil options:nil] firstObject];
    }
    return cell;
}


// set方法
- (void)setItem:(NSString *)item {
    _item = item;
    
    NSString *docPath =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath = [docPath stringByAppendingPathComponent:item];
    
    // 把模型的数据，设置给子控件。
    self.lblName.text = item;
    
    NSRange range;
    if([item hasSuffix:@".mp4"]) { // 视频
        range = [item rangeOfString:@".mp4"];
        // TODO 显示视频的第一帧画面。 handleVideoImgWithFileName
        [self handleVideoImgWithFileName:item andImageView:self.imageViewIcon];
    } else {
        range = [item rangeOfString:@".png"];
        self.imageViewIcon.image = [[UIImage alloc] initWithContentsOfFile:filePath];
    }
    range.length = range.location;
    range.location =0;
    NSString *desc = [item substringWithRange:range]; // 获取文件无尾缀的名称。
    
    if([item hasSuffix:@".mp4"]) {
        // 获取视频的时长：01:22
        NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:item];
        NSURL *nsUrl = [NSURL fileURLWithPath:filePath];
        NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
        AVURLAsset *asset = [AVURLAsset URLAssetWithURL:nsUrl options:opts];
        CMTime time = [asset duration];
        NSInteger second = ceil(time.value/time.timescale);
        int minutes = (int)(second / 60); // 分钟数
        int seconds = second % 60; // 秒数
        self.lblDesc.text = [NSString stringWithFormat:@"%02d:%02d", minutes, seconds];
    } else {
        self.lblDesc.text = desc; // 去掉尾缀
    }
    self.videoPlayIcon.hidden = ![item hasSuffix:@".mp4"]; // 显示播放三角形
}

// 异步处理显示图片。
-(void) handleVideoImgWithFileName:(NSString *)fileName andImageView:(UIImageView *)imageView {
    NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
    NSURL *nsUrl = [NSURL fileURLWithPath:filePath];
    
    AVAsset *asset = [AVAsset assetWithURL:nsUrl];
    AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    // 开始生成图像 time用来表示影片的时间的值。
    // 参数1 第几秒 ；timescale 代表视频的每秒的帧数
    CMTime  time = CMTimeMake(2, 1); // 要截取那一帧(秒)，截取第30s的。
    NSValue *value = [NSValue valueWithCMTime:time];
    [imageGenerator generateCGImagesAsynchronouslyForTimes:@[value] completionHandler:^(CMTime requestedTime, CGImageRef  _Nullable image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError * _Nullable error) {
        dispatch_sync(dispatch_get_main_queue(), ^{
            // 在主线程更新UI。异步方法。
            imageView.image = [UIImage imageWithCGImage:image];
        });
    }];
}

@end

